const path = require("path");

const fs = require("fs");

const json = path.resolve(__dirname, "./tsconfig.json");

const data = fs.readFileSync(json, "utf-8");

let pathList = data.match(/"@.*?\]/gm);

let outDir = data.match(/(?<="outDir":.").*/g)[0].match(/.*(?=",)/g)[0]; // 前瞻后瞻选出outDir

let baseUrl = data.match(/(?<="baseUrl":.").*/g)[0].match(/.*(?=",)/g)[0]; // 前瞻后瞻选出baseUrl

let handlePathList: string[] = [];

const os = require("os");

const isMAC = os.platform() === "darwin";

for (let i = 0; i < pathList.length; i++) {
  handlePathList.push(
    pathList[i]
      .match(/".*?"/g)
      .map((item: string) => item.replace(/"/g, "").replace(/\/\*/g, ""))
  ); // 处理paths为二维数组
}

function deepdir(path: string, usePath: string) {
  const files = fs.readdirSync(path);
  files.forEach((item: string) => {
    try {
      let isRewrite: boolean = false;
      let content: string = fs.readFileSync(
        path + (isMAC ? "/" : "\\") + item,
        "utf-8"
      );
      handlePathList.forEach((items: string) => {
        // 替换字符串
        const handleUsePath = usePath === "" ? "./" : usePath;
        let url = items[1].startsWith("./")
          ? items[1].replace("./", handleUsePath)
          : handleUsePath + items[1];
        let matchRes: RegExpMatchArray = content.match(
          new RegExp(items[0], "g")
        );
        if (matchRes) {
          // 优化
          content = content.replace(new RegExp(items[0], "g"), url);
          isRewrite = true;
        }
      });
      if (isRewrite)
        fs.writeFileSync(path + (isMAC ? "/" : "\\") + item, content, "utf-8");
    } catch {
      deepdir(path + "/" + item, "../" + usePath);
    }
  });
}

deepdir(outDir + baseUrl, "");

console.info("文件引用路径处理完成！");
